package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.dao.FootRankDao;
import org.footballmanager.pandafootball.system.domain.FootQd;
import org.footballmanager.pandafootball.system.domain.FootRank;
import org.footballmanager.pandafootball.system.domain.FootTeam;
import org.footballmanager.pandafootball.system.domain.FootUser;
import org.footballmanager.pandafootball.system.form.impl.FootRankSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootRankMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FootRankServiceImpl extends RepeatServiceImpl<FootRank> implements FootRankService {
	private static final double TOP1 = 30d;
	private static final double TOP2 = 20d;
	private static final double TOP3 = 10d;
	
    @Autowired
    private FootRankMapper footRankMapper;
    @Autowired
    private FootRankDao footRankDao;
	@Autowired
	private FootUserService footUserService;
	@Autowired
	private FootTeamService footTeamService;
	@Autowired
	private FootSjService footSjService;
	@Autowired
	private FootZnxService footZnxService;
	@Autowired
	private FootZjService footZjService;

	/**
	 * 获取积分榜
	 */
    @Override
	public List<FootRank> getScoreboard() {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo( "sj", footSjService.getSj());
        criteria.andIsNotNull("name");
        criteria.andNotEqualTo("name", "");
        example.orderBy("jf desc, jsq desc, jq desc");
		List<FootRank> list = findall(example);
		if(list != null && !list.isEmpty()){
			return list;
		}else{
			return Collections.emptyList();
		}
	}
	
	/**
	 * 根据用户取俱乐部信息
	 */
    @Override
	public FootRank findByUserid(Long userId){
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo( "sj", footSjService.getSj());
        criteria.andEqualTo(Constants.USERID, userId);
		FootRank ft = this.findByExample(example);
		if(ft != null){
			return ft;
		}
		return null;
	}

	@Transactional
    @Override
	public void reComputeRanking(HttpServletRequest request) {
		List<FootRank> list = this.getScoreboard();
		if(null != list && !list.isEmpty()){
			int i = 1;
			for(FootRank fc: list){
				fc.setPm(i++);
                fc.setUpdateId((Long)request.getSession().getAttribute(Constants.USER));
                fc.setUpdateTime(new Date());
                footRankDao.updateByPrimaryKeySelective(fc);
			}
		}
	}

    @Override
	public List<FootRank> getRanksByUserid(Long userId) {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
		return this.findall(example);
	}

    @Override
	public void saveNewRank(FootUser user, Long qdId, HttpServletRequest request) {
		FootRank fc = new FootRank();
		fc.setQdId(qdId);
		fc.setBscc(0);
		fc.setS(0);
		fc.setF(0);
		fc.setP(0);
		fc.setSl(0D);
		fc.setSq(0);
		fc.setJf(0);
		fc.setJq(0);
		fc.setJsq(0);
		fc.setUserId(user.getId());
		fc.setUserName(user.getNike());
		fc.setSj(footSjService.getSj());
		this.save(fc, request);
	}

    @Override
	public void updateRankQdName(Long userId, FootQd qd, HttpServletRequest request) {
		FootRank rank = this.findByUserid(userId);
		if(null != rank){
			rank.setQdName(qd.getQdmc());
			this.updateNotNull(rank, request);
		}
	}

    @Override
	public void reward(HttpServletRequest request) {
		List<FootRank> list = this.getScoreboard();
		if(!list.isEmpty()){
			//第一名
			FootRank rank1 = list.get(0);
			if(null != rank1){
				this.rewardTop3(rank1, "一", request);
			}
		}
		if(list.size() > 1){
			//第二名
			FootRank rank2 = list.get(1);
			if(null != rank2){
				this.rewardTop3(rank2, "二", request);
			}
		}
		if(list.size() > 2){
			//第三名
			FootRank rank3 = list.get(2);
			if(null != rank3){
				this.rewardTop3(rank3, "三", request);
			}
		}
	}

	private void rewardTop3(FootRank rank, String top, HttpServletRequest request) {
		if(rank != null){
			FootTeam team = footTeamService.getTeamByUserid(rank.getUserId());
			double money = 0D;
			switch (top){
                case "一":
                    money = TOP1;
                    break;
                case "二":
                    money = TOP2;
                    break;
                case "三":
                    money = TOP3;
                    break;
                default:
                    break;
            }
			team.setQdZzj(team.getQdZzj() + money);
			String result = "恭喜您,获得排位赛第" + top + "名,发放奖金€" + 
				    new DecimalFormat(",###").format(money) + ",当前总资金为:€" +
                    new DecimalFormat(",###").format(team.getQdZzj());
			footZnxService.sendZnx(footUserService.getAdminUserid(), team.getUserId(), result, null, null, request);
			footZjService.sendZj(team.getUserId(), money, true, result, request);
			footTeamService.updateNotNull(team, request);
		}
	}

    @Override
	public boolean findRepeatData(FootRank newrank) {
        Example example = new Example(FootRank.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qdId", newrank.getQdId());
        criteria.andEqualTo(Constants.USERID, newrank.getUserId());
        criteria.andEqualTo("sj", newrank.getSj());
        List<FootRank> list = this.findall(example);
        return null != list && !list.isEmpty();
	}

    /**
     * 翻页方法
     *
     * @param footRankSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootRank> findall(FootRankSearchForm footRankSearchForm) {
        return footRankMapper.findall(footRankSearchForm);
    }

	/**
	 * 根据主键获取记录
	 * @param id 主键
	 * @return 记录
	 */
	@Override
	public FootRank get(Serializable id) {
		return footRankMapper.findById(id);
	}

    /**
     * 查询
     *
     * @param entityname         实体类名
     * @param map                参数
     * @param footRankSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootRankSearchForm footRankSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footRankSearchForm);
        Page<FootRank> page = PageHelper.startPage(footRankSearchForm.getPageIndex(), footRankSearchForm.getPageSize());
        List<FootRank> list = this.findall(footRankSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }
}
